package com.bookcycle.panda.file.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;


/**
 * @author Mason
 * @date 2018/3/8
 */
@Controller
@RequestMapping("file")
public class FileController extends BaseController{
    private Logger logger= LoggerFactory.getLogger(this.getClass());
    private final String RESOURCE_PATH="./files";
    private final String PORT="8132";
    private final String HOST="http://47.106.122.242:";

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String file(){
        return "fileTest";
    }
    /**
     *
     * @param file
     * @param filepath
     * @return
     */
    @CrossOrigin
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file,
                                              @RequestParam("filepath") String filepath){
        String filename=file.getOriginalFilename();
        try {
            File targetFilePath=new File(this.RESOURCE_PATH+filepath);
            if(!targetFilePath.exists()){
                targetFilePath.mkdirs();
            }
            File file1=new File(targetFilePath+"/"+filename);
            file1.createNewFile();
            FileOutputStream fileOutputStream=new FileOutputStream(file1);
            fileOutputStream.write(file.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
            return ResponseEntity.status(HttpStatus.OK).body(this.HOST+this.PORT+filepath+"/"+filename);
        }catch (UnknownHostException uhe){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }catch (IOException ioe){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    /**
     *
     * @param filename
     * @param filepath
     * @return
     */
    @RequestMapping(value = "/getFile",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<File> getImage(@RequestParam("filename") String filename,
                                         @RequestParam("filepath") String filepath) {
        File file=new File(this.RESOURCE_PATH+filepath+"/"+filename);

        if(!file.exists()){
            return ResponseEntity.status(HttpStatus.NO_CONTENT).body(null);
        }
        return ResponseEntity.status(HttpStatus.OK).body(file);

    }
}
